import seedAgent from '@/services/seedAgent-service';
import { Button, Form, Input, InputNumber, message } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

const { TextArea } = Input;

interface SeedAgentFormProps {
  initialValues?: any;
  onSuccess?: () => void;
  mode?: 'create' | 'edit';
}

const SeedAgentForm: React.FC<SeedAgentFormProps> = ({
  initialValues,
  onSuccess,
  mode = 'create',
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (initialValues) {
      form.setFieldsValue({
        ...initialValues,
        create_date: initialValues.create_date
          ? dayjs(initialValues.create_date)
          : null,
        update_date: initialValues.update_date
          ? dayjs(initialValues.update_date)
          : null,
      });
    }
  }, [initialValues, form]);

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        ...values,
        create_date: values.create_date?.toISOString(),
        update_date: values.update_date?.toISOString(),
      };

      if (mode === 'create') {
        await seedAgent.seed_agent_create(payload);
        message.success('种子代理创建成功');
      } else {
        await seedAgent.seed_agent_update({
          agent_id: initialValues.agent_id,
          ...payload,
        });
        message.success('种子代理更新成功');
      }

      if (onSuccess) onSuccess();
    } catch (error) {
      message.error('操作失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      initialValues={initialValues}
    >
      <Form.Item
        name="purpose"
        label="目的"
        rules={[{ required: true, message: '请输入目的' }]}
      >
        <Input placeholder="请输入目的" />
      </Form.Item>

      <Form.Item
        name="data_source"
        label="数据源"
        rules={[{ required: true, message: '请输入数据源' }]}
      >
        <Input placeholder="请输入数据源" />
      </Form.Item>

      <Form.Item name="knowledge_base" label="知识库">
        <Input placeholder="请输入知识库" />
      </Form.Item>

      <Form.Item name="importance" label="重要性">
        <InputNumber min={1} max={10} placeholder="请输入重要性(1-10)" />
      </Form.Item>

      <Form.Item name="description" label="描述">
        <TextArea rows={4} placeholder="请输入描述信息" />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading}>
          {mode === 'create' ? '创建' : '更新'}
        </Button>
      </Form.Item>
    </Form>
  );
};

export default SeedAgentForm;
